package com.zzh.bc.utils;

import com.google.gson.Gson;
import com.zzh.bc.callback.LogCallback;
import jakarta.servlet.http.HttpServletRequest;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Optional;

public class RequestParamUtils {

    private static final Gson mGson;

    static {
        mGson = new Gson();
    }

    public static void logReqParams(HttpServletRequest request) {
        if (request == null) {
            return;
        }

        System.out.println("--------------请求参数开始-------------");
        Enumeration<String> attributeNames = request.getParameterNames();
        Enumeration<String> headerNames = request.getHeaderNames();
        logParams(request, attributeNames, key->System.out.println("params key: "+key+"， value: "+request.getParameter(key)));
        logParams(request, headerNames, key->System.out.println("header key: "+key+"， value: "+request.getHeader(key)));

        System.out.println("--------------请求参数结束-------------");
    }

    private static void logParams(HttpServletRequest request, Enumeration<String> attributeNames, LogCallback callback) {
        if (attributeNames != null){
            while (attributeNames.hasMoreElements()){
                String element = attributeNames.nextElement();
                if (callback != null){
                    callback.logReq(element);
                }
            }
        }
    }

    public static <T> T requestBodyParams(HttpServletRequest request, Class<T> clz) {
        if (request == null) {
            return null;
        }
        Optional<T> optional;
        logReqParams(request);
        try {
            request.setCharacterEncoding("UTF-8");
            BufferedReader reader = request.getReader();
            String read = reader.readLine();
            reader.close();
            System.out.println("----接收数据：" + read);
            return mGson.fromJson(read, clz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> Optional<T> safeRequestBodyParams(HttpServletRequest request, Class<T> clz) {
        if (request == null) {
            return Optional.empty();
        }
        Optional<T> optional = Optional.empty();
        logReqParams(request);
        try {
            request.setCharacterEncoding("UTF-8");
            BufferedReader reader = request.getReader();
            String read = reader.readLine();
            reader.close();
            System.out.println("----接收数据：" + read);
            T t = mGson.fromJson(read, clz);
            return Optional.of(t);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return optional;
    }

}
